import java.io.*;

public class FileReplaceTool {
    public static void main(String[] args) {
        // Validate command line arguments
        if (args.length != 4) {
            System.err.println("Usage: java FileReplaceTool <inputFile> <outputFile> <oldString> <newString>");
            System.exit(1);
        }

        String inputFile = args[0];
        String outputFile = args[1];
        String oldString = args[2];
        String newString = args[3];

        try {
            replaceFileContent(inputFile, outputFile, oldString, newString);
            System.out.println("File content replacement completed successfully.");
        } catch (IOException e) {
            System.err.println("Error processing file: " + e.getMessage());
            System.exit(1);
        }
    }

    private static void replaceFileContent(String inputFile, String outputFile,
                                           String oldString, String newString) throws IOException {
        // Create temporary file for writing
        File tempFile = new File(outputFile);

        // Ensure output directory exists
        File parentDir = tempFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // Use BufferedReader and BufferedWriter for efficient processing
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {

            String line;
            // Read and process file line by line to handle large files
            while ((line = reader.readLine()) != null) {
                // Replace all occurrences of oldString with newString
                String modifiedLine = line.replace(oldString, newString);
                // Write modified line to output file
                writer.write(modifiedLine);
                writer.newLine();
            }
        } catch (FileNotFoundException e) {
            throw new IOException("Input file not found: " + inputFile, e);
        } catch (IOException e) {
            throw new IOException("Error reading or writing file: " + e.getMessage(), e);
        }
    }
}